#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/22 13:20
# @Author  : CoderCharm
# @File    : security.py
# @Software: PyCharm
# @Github  : github/CoderCharm
# @Email   : wg_python@163.com
# @Desc    :
"""
token password 验证
pip install python-jose
pip install passlib
pip install bcrypt
安装不上尝试 python -m pip install --no-use-pep517 bcrypt

"""
import jwt
from datetime import datetime, timedelta
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from conf.config import jwt_config, app_config
from utils.common_helper import get_date

OAuth2 = OAuth2PasswordBearer(tokenUrl="/admin/access-token")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def create_access_token(data: dict,  expire_minutes=jwt_config.ADMIN_ACCESS_TOKEN_EXPIRE_MINUTES,
                        secret_key=app_config.SECRET_KEY, algorithm=jwt_config.ALGORITHM, return_expire_timestamp=False):
    """
    创建token
    :param data:
    :param expire_minutes:
    :param secret_key:
    :param algorithm:
    :param return_expire_timestamp:
    :return:
    """
    to_encode = data.copy()
    # token超时时间
    expire = datetime.now() + timedelta(minutes=expire_minutes)

    # 超时时间 时间戳
    expire_timestamp = get_date(expire, out_fmt="timestamp")

    # 向jwt加入超时时间
    to_encode.update({"exp": expire_timestamp})
    # jwt加密
    encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=algorithm)

    if return_expire_timestamp:
        return encoded_jwt, expire_timestamp
    return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    验证密码
    :param plain_password: 原密码
    :param hashed_password: hash后的密码
    :return:
    """
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    """
    获取 hash 后的密码
    :param password:
    :return:
    """
    return pwd_context.hash(password)


